﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CNRS.CCP.Connector;
using CNRS.CCP.Config;
using CNRS.CCP.DAO;
using System.Net;
using Newtonsoft.Json;
using System.IO;



namespace CNRS.CCP.Connector
{
	public class VootConnector
	{
		/// <summary>
		/// Search in a particular node RefList to found a match
		/// </summary>
		/// <param name="searchPattern"></param>
		/// <param name="node"></param>
		public static List<DataElement> GetDataElements(string searchPattern, ClaimElement element)
		{
			LogHelper.LogDebug(LogCategorie.VootHelper, string.Format("Searching '{0}' for 'element' -> '{1}'", searchPattern, element.ClaimType));


			List<DataElement> dataElements = null;
			string json = string.Empty;

			if (!string.IsNullOrEmpty(searchPattern))
			{
				Provider provider = ClaimsParameters.Instance.GrouperProvider;

				string searchUrl = provider.Server + "?search=" + searchPattern;
				// TODO : work out search in Grouper

				HttpWebRequest request = (HttpWebRequest)WebRequest.Create(searchUrl);
				request.Method = "GET";
				//request.ContentType = "application/json";

				string autorization = provider.User + ":" + provider.Password;
				byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
				autorization = Convert.ToBase64String(binaryAuthorization);
				autorization = "Basic " + autorization;
				request.Headers.Add("AUTHORIZATION", autorization);

				try
				{

					// call grouper voot web service
					HttpWebResponse response = (HttpWebResponse)request.GetResponse();
					if (response.StatusCode != HttpStatusCode.OK)
					{
						LogHelper.LogError(("http status code : " + response.StatusCode), response.Headers.ToString());
					}
					else
					{
						// store the response in a string
						using (Stream responseStream = response.GetResponseStream())
						{
							StreamReader stream = new StreamReader(responseStream, Encoding.UTF8);
							json = stream.ReadToEnd();
							stream.Close();
						}

						// transform the json string to .Net object
						var res = JsonConvert.DeserializeObject<GrouperEntry>(json);

						if (res != null && res.entry != null)
						{
							dataElements = new List<DataElement>();
							// transform grouper entry to dataElement
							foreach (Entry item in res.entry)
							{
								DataElement jsonElement = new DataElement();
								jsonElement.Value = item.id;

								dataElements.Add(jsonElement);
							}
							LogHelper.LogDebug(LogCategorie.VootHelper, string.Format("Elements returned -> '{0}'", dataElements.Count));
						}
					}
				}
				catch (WebException ex)
				{
					WebResponse errorResponse = ex.Response;
					using (Stream responseStream = errorResponse.GetResponseStream())
					{
						StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
						String errorText = reader.ReadToEnd();
						LogHelper.LogError(ex, errorText);

					}
				}
			}
			return dataElements;
		}
	}

	public class Entry
	{
		public string description { get; set; }
		public string id { get; set; }
		public string name { get; set; }
	}

	public class GrouperEntry
	{
		public List<Entry> entry { get; set; }
		public int itemsPerPage { get; set; }
		public int startIndex { get; set; }
		public int totalResults { get; set; }
	}
}
